package work.io.aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {


    /*

        异步通信工作过程


     */

    //线程池
    private ExecutorService executorService;

    //ServerSocket
    private AsynchronousServerSocketChannel channel;

    private int port;

    //创建一个服务端
    public Server(int port) {
        this.port = port;
    }

    //初始化
    public void init() {

        //创建一个线程池
        executorService = Executors.newFixedThreadPool(8);

        try {

            //可以使用线程池

            //开启服务端通道
            channel = AsynchronousServerSocketChannel.open();

            //绑定监听端口
            channel.bind(new InetSocketAddress(port));

            //开始监听,第一个参数是通道依附,可以使用第一个参数获取通道
            //第二个参数则是一个带有泛型的处理器.第一个泛型只能是AsynchronousSocketChannel
            channel.accept(this, new MyCompletionHandler());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public AsynchronousServerSocketChannel getChannel() {
        return channel;
    }


    public static void main(String[] args) throws InterruptedException {

        Server server = new Server(8080);

        server.init();

        System.out.println("监听已经开始");

        Thread.sleep(1000000);

    }


}
